// pages/forensics/pages/indexv/index.js

var app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        roomID: '',
        headerHeight: app.globalData.headerHeight,
        statusBarHeight: app.globalData.statusBarHeight,
        is_notary:0,
        record_id:0,
        invitee: {
            userID:'',
        },
        config_base : {
            sdkAppID: 1400756039,
            userID: '',
            userSig: '',
        },
        config: {
            sdkAppID: 1400756039,
            // 就是手机号
            userID: '',
            userSig: '',
            // type: MEDIA_TYPE.VIDEO,
            tim: null,
        },
        caller:null,
        listener:null,
        message:'',
        
    },
    enterRoomID(event) {
        this.setData({
            roomID: event.detail.value,
        })
    },
    // enterRoom() {
    //     const {
    //         roomID
    //     } = this.data
    //     const nowTime = new Date()
    //     if (nowTime - this.tapTime < 1000) {
    //         return
    //     }
    //     if (!roomID) {
    //         wx.showToast({
    //             title: '请输入房间号',
    //             icon: 'none',
    //             duration: 2000,
    //         })
    //         return
    //     }
    //     if (/^\d*$/.test(roomID) === false) {
    //         wx.showToast({
    //             title: '房间号只能为数字',
    //             icon: 'none',
    //             duration: 2000,
    //         })
    //         return
    //     }
    //     if (roomID > 4294967295 || roomID < 1) {
    //         wx.showToast({
    //             title: '房间号取值范围为 1~4294967295',
    //             icon: 'none',
    //             duration: 2000,
    //         })
    //         return
    //     }

    //     const userID = this.data.config.userID
    //     const Signature = this.data.config.userSig
    //     const sdkAppID = this.data.config.sdkAppID
    //     const url = `/pages/forensics/pages/videocall/index?roomID=${roomID}&userID=${userID}&sdkAppID=${sdkAppID}&userSig=${Signature}`
    //     this.tapTime = nowTime
    //     this.checkDeviceAuthorize().then((result) => {
    //             console.log('授权成功', result)
    //             wx.navigateTo({
    //                 url
    //             })
    //         })
    //         .catch((error) => {
    //             console.log('没有授权', error)
    //         })
    // },

    enterRoom(){
        wx.join1v1Chat({
            caller: this.data.caller,
            listener: this.data.listener,
            roomType:'video',
            success: res => {
                console.log('成功');
                console.log(res);
            },
            fail:res => {
                console.log('失败');
                console.log(res);
            },
        })
    },
    enterRoomNew(){
      wx.navigateTo({
        url: '/pages/forensics/pages/videobaiduv/index?room_id='+this.data.roomID +'&message='+this.data.message,
    })
  
      // wx.join1v1Chat({
      //     caller: this.data.caller,
      //     listener: this.data.listener,
      //     roomType:'video',
      //     success: res => {
      //         console.log('成功');
      //         console.log(res);
      //     },
      //     fail:res => {
      //         console.log('失败');
      //         console.log(res);
      //     },
      // })
  },

    checkDeviceAuthorize() {
        this.hasOpenDeviceAuthorizeModal = false
        return new Promise((resolve, reject) => {
            if (!wx.getSetting || !wx.getSetting()) {
                // 微信测试版 获取授权API异常，目前只能即使没授权也可以通过
                resolve()
            }
            wx.getSetting().then((result) => {
                console.log('getSetting', result)
                this.authorizeMic = result.authSetting['scope.record']
                this.authorizeCamera = result.authSetting['scope.camera']
                if (result.authSetting['scope.camera'] && result.authSetting['scope.record']) {
                    // 授权成功
                    resolve()
                } else {
                    // 没有授权，弹出授权窗口
                    // 注意： wx.authorize 只有首次调用会弹框，之后调用只返回结果，如果没有授权需要自行弹框提示处理
                    console.log('getSetting 没有授权，弹出授权窗口', result)
                    wx.authorize({
                            scope: 'scope.record',
                        }).then((res) => {
                            console.log('authorize mic', res)
                            this.authorizeMic = true
                            if (this.authorizeCamera) {
                                resolve()
                            }
                        })
                        .catch((error) => {
                            console.log('authorize mic error', error)
                            this.authorizeMic = false
                        })
                    wx.authorize({
                            scope: 'scope.camera',
                        }).then((res) => {
                            console.log('authorize camera', res)
                            this.authorizeCamera = true
                            if (this.authorizeMic) {
                                resolve()
                            } else {
                                this.openConfirm()
                                reject(new Error('authorize fail'))
                            }
                        })
                        .catch((error) => {
                            console.log('authorize camera error', error)
                            this.authorizeCamera = false
                            this.openConfirm()
                            reject(new Error('authorize fail'))
                        })
                }
            })
        })
    },
    openConfirm() {
        if (this.hasOpenDeviceAuthorizeModal) {
            return
        }
        this.hasOpenDeviceAuthorizeModal = true
        return wx.showModal({
            content: '您没有打开麦克风和摄像头的权限，是否去设置打开？',
            confirmText: '确认',
            cancelText: '取消',
            success: (res) => {
                this.hasOpenDeviceAuthorizeModal = false
                console.log(res)
                // 点击“确认”时打开设置页面
                if (res.confirm) {
                    console.log('用户点击确认')
                    wx.openSetting({
                        success: (res) => {},
                    })
                } else {
                    console.log('用户点击取消')
                }
            },
        })
    },
    // to_call() {
        // // this.TUICallKit.call({
        // //     userID: 'jane',
        // //     type: MEDIA_TYPE.VIDEO
        // // });

        // // this.setData(
        // //     {
        // //         config: { ...this.data.config, ...this.data.config_base },
        // //     },
        // //     () => {
        // //         this.TUICallKit = this.selectComponent('#TUICallKit-component');
        // //         this.TUICallKit.init();
        // //     },
        // // );
        // console.log(this.data.config);
        // console.log(this.data.invitee);
        // if (this.data.config.userID === this.data.invitee.userID) {
        //     wx.showToast({
        //       icon: 'none',
        //       title: '不可呼叫本机',
        //     });
        //     return;
        //   }
        //   try {
        //     await this.TUICallKit.call({ userID: this.data.invitee.userID, type: MEDIA_TYPE.VIDEO });
        //   } catch (error) {
        //     wx.showModal({
        //       icon: 'none',
        //       title: 'error',
        //       content: error.message,
        //       showCancel: false,
        //     });
        //   }

    // },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
    
        this.setData({
            record_id:options.record_id,
            roomID:options.record_id,
        })
        if(typeof options.is_notary != 'undefined'){
            let is_notary = options.is_notary
            this.setData({
                is_notary:is_notary
            })
        }
        // let url = 'data/api.auth.order/getSign';
        // let params = {
        //     record_id:options.record_id,
        // }
        // if(this.data.is_notary > 0){
        //     url = 'data/api.login/getSign';
        //     params.is_notary = this.data.is_notary
        // }
        // getApp()._post_form(url, params, results => {
        //     this.data.config.userID = results.data.phone
        //     this.data.config.userSig = results.data.sign

        //     this.data.config_base.userID = results.data.phone
        //     this.data.config_base.userSig = results.data.sign
        //     console.log(this.data.config);
        //     //公证员id
        //     this.data.invitee.userID =results.data.system_user_id
        //     // this.setData(
        //     //     {
        //     //         config: { ...this.data.config, ...this.data.config_base },
        //     //     },
        //     //     () => {
        //     //         this.TUICallKit = this.selectComponent('#TUICallKit-component');
        //     //         this.TUICallKit.init();
        //     //     },
        //     // );

        // });
        wx.authorize({
            scope: 'scope.record',
            success: res => {
                wx.authorize({
                    scope: 'scope.camera',
                    success: res => {
                        wx.setEnable1v1Chat({
                            enable: true
                        })
                    }
                })
            }
        })

        let url = 'data/api.auth.order/getParams';
        let params = {
            record_id:options.record_id,
        }
        if(this.data.is_notary > 0){
            url = 'data/api.login/getParams';
            params.is_notary = this.data.is_notary
        }
        getApp()._post_form(url, params, results => {
            console.log(results);
            this.setData({
                caller:results.data.caller,
                listener:results.data.listener,
                message:results.data.message,
            })
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        this.TUICallKit.destroyed();
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
      const roomID = this.data.roomID; // 获取需要传递的参数
      return {
        title: '自定义转发标题', // 转发标题
        path: `/pages/home/index?record_id=${roomID}`, // 转发路径，携带参数
        imageUrl: '/images/share.jpg' // 转发图片（可选）
      };
    }
})